package com.hos.operation.api;


import com.hos.db.entity.ArtEntity;
import com.hos.db.entity.SmsEntity;
import com.hos.db.entity.UserDocEntity;
import com.hos.db.entity.UserPatsEntity;
import com.hos.db.entity.consult.ConsultChatEntity;
import com.hos.db.entity.consult.ConsultPatEntity;
import com.hos.db.entity.msg.MsgEntity;
import com.hos.db.entity.visit.VisitEntityPat;
import com.hos.db.manager.ArtManager;
import com.hos.db.manager.ConsultChatManager;
import com.hos.db.manager.ConsultManager;
import com.hos.db.manager.DocsManager;
import com.hos.db.manager.MsgManager;
import com.hos.db.manager.RelationManager;
import com.hos.db.manager.SMSManager;
import com.hos.db.manager.VisitsManager;
import com.hos.net.DictionariesDocService;
import com.hos.net.DictionariesFileService;
import com.hos.net.DictionariesIllService;
import com.hos.net.req.BaseReq;
import com.hos.net.req.consult.ConsultChatAddReq;
import com.hos.net.req.consult.ConsultChatsReq;
import com.hos.net.req.consult.ConsultIdReq;
import com.hos.net.req.consult.ConsultsReq;
import com.hos.net.req.doc.DocLoginReq;
import com.hos.net.req.doc.DocRegisterReq;
import com.hos.net.req.doc.DocRestPwdReq;
import com.hos.net.req.doc.DocUpdateReq;
import com.hos.net.req.push.PushReq;
import com.hos.net.req.relation.RelationRemarkReq;
import com.hos.net.req.sms.SmsReq;
import com.hos.net.req.sms.SmsVerifyReq;
import com.hos.net.req.visit.VisisReq;
import com.hos.net.req.visit.VisitAddReq;
import com.hos.net.req.visit.VisitDeleteReq;
import com.hos.net.req.visit.VisitMsgReq;
import com.hos.net.req.visit.VisitUpdateReq;
import com.hos.net.res.BaseResponse;
import com.hos.net.res.MsgHint;
import com.hos.net.res.PageData;
import com.hos.net.res.loading.Upload7NRes;
import com.hos.operation.manager.ConstantData;
import com.hos.operation.manager.Yun7NManager;
import com.hos.utile.DLog;
import com.hos.utile.JsonUtile;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

@Controller
public class ApiDocController extends ApiBaseCommunal {

    @RequestMapping(value = "/doc", method = RequestMethod.POST,
            produces = "application/json;charset=UTF-8")
    @ResponseBody
    public String app(HttpServletRequest request, @RequestBody String json) {
        BaseReq req = isVerifyDataJson(request, json,"doc");
        if (!req.isVerify) {
            return req.errorMsg;
        }
        //
        String service = req.service;
        String response = "";
        switch (service) {
            case DictionariesDocService.HOS_DOC_SMS_VERIFY:
                //验证码验证
                SmsVerifyReq smsVerifyReq = (SmsVerifyReq) JsonUtile.json2Obj(json, SmsVerifyReq.class);
                if (!smsVerifyReq.isVerifyParameter()) {
                    return smsVerifyReq.hint;
                }
                SmsEntity sms = SMSManager.getInstance().getSms(getJdbcTemplate(),
                        smsVerifyReq.phone, smsVerifyReq.type, smsVerifyReq.code);
                if (sms == null) {
                    response = new MsgHint("-1", "验证码无效").toJson();
                    DLog.e("没有发送验证码");
                    break;
                }
                //已经使用过了
                if (sms.isSmsIsVerifyIs()) {
                    response = new MsgHint("-1", "验证码无效").toJson();
                    DLog.e("已经使用过了");
                    break;
                }
                //超时
                long time = new Date().getTime() - sms.getSmsSendTime().getTime();
                if (time > ConstantData.SMS_OUT_TIME) {
                    response = new MsgHint("-1", "验证码无效").toJson();
                    SMSManager.getInstance().deleteSms(getJdbcTemplate(), sms.getSmsId());
                    DLog.e("验证码超时");
                    break;
                }
                //删除验证码
                SMSManager.getInstance().deleteSms(getJdbcTemplate(), sms.getSmsId());
                response = new MsgHint("0", "验证成功").toJson();
                break;
            case DictionariesDocService.HOS_DOC_SMS_REST_PWD:
                //医生重置密码发送验证码
                SmsReq smsReq = (SmsReq) JsonUtile.json2Obj(json, SmsReq.class);
                if (!smsReq.isVerifyParameter("7")) {
                    return smsReq.hint;
                }
                UserDocEntity user = DocsManager.getInstance().getUserForPhone(getJdbcTemplate(), smsReq.phone);
                if (user == null) {
                    response = new MsgHint("-1", "该账号不存在").toJson();
                    break;
                }
                //发送验证码
                response = SMSManager.getInstance().smsSend(getJdbcTemplate(), smsReq);
                break;
            case DictionariesDocService.HOS_DOC_SMS_REG:
                //医生注册发送验证码
                smsReq = (SmsReq) JsonUtile.json2Obj(json, SmsReq.class);
                if (!smsReq.isVerifyParameter("6")) {
                    return smsReq.hint;
                }
                user = DocsManager.getInstance().getUserForPhone(getJdbcTemplate(), smsReq.phone);
                if (user != null) {
                    response = new MsgHint("-1", "该账号已经存在").toJson();
                    break;
                }
                //发送验证码
                response = SMSManager.getInstance().smsSend(getJdbcTemplate(), smsReq);
                break;
            //===========个人============================
            case DictionariesDocService.HOS_DOC_REG:
                //注册
                DocRegisterReq regReq = (DocRegisterReq) JsonUtile.json2Obj(json,
                        DocRegisterReq.class);
                if (!regReq.isVerifyParameter()) {
                    return regReq.hint;
                }
                response = DocsManager.getInstance().docRegister(getJdbcTemplate(), regReq);
                break;
            case DictionariesDocService.HOS_DOC_LOGIN:
                //医生登录
                DocLoginReq docLoginReq = (DocLoginReq) JsonUtile.json2Obj(json, DocLoginReq.class);
                if (!docLoginReq.isVerifyParameter()) {
                    return docLoginReq.hint;
                }
                response = DocsManager.getInstance()
                        .userLoginReq(getJdbcTemplate(), docLoginReq.account,
                                docLoginReq.pwd, docLoginReq.pushId);
                break;
            case DictionariesDocService.HOS_DOC_UPDATE:
                //医生修改个人信息
                UserDocEntity doc = verifyTokenUser(req.token);
                if (doc == null) {
                    response = new MsgHint("100", "登陆过期，请重新登陆").toJson();
                    break;
                }
                DocUpdateReq docUpdateReq = (DocUpdateReq) JsonUtile.json2Obj(json, DocUpdateReq.class);
                docUpdateReq.docId = doc.getDocId();
                response = DocsManager.getInstance()
                        .updateUserReq(getJdbcTemplate(), docUpdateReq);
                break;
            case DictionariesDocService.HOS_DOC_REST_PWD:
                //医生重置密码
                DocRestPwdReq docRestPwdReq = (DocRestPwdReq) JsonUtile.json2Obj(json, DocRestPwdReq.class);
                if (!docRestPwdReq.isVerifyParameter()) {
                    return docRestPwdReq.hint;
                }
                response = DocsManager.getInstance()
                        .updateRestPwdReq(getJdbcTemplate(), docRestPwdReq.phone, docRestPwdReq.pwd);
                break;
            //===========随访============================
            case DictionariesDocService.HOS_DOC_VISS:
                doc = verifyTokenUser(req.token);
                if (doc == null) {
                    response = new MsgHint("100", "登陆过期，请重新登陆").toJson();
                    break;
                }
                //
                VisisReq visisReq = (VisisReq) JsonUtile.json2Obj(json, VisisReq.class);
                List<VisitEntityPat> list = VisitsManager.getInstance().onPatVisitsReq(getJdbcTemplate(),
                        doc.getDocId(), visisReq.isComplete, req.pageNo,
                        req.pageSize, true);
                int patSize = list.size();
                BaseResponse baseRes = new BaseResponse();
                PageData pageData = new PageData();
                if (patSize > req.pageSize) {
                    //有下一页
                    list.remove(patSize - 1);
                    pageData.hasNextPage = true;
                }
                pageData.pageNo = req.pageNo;
                pageData.pageSize = list.size();
                baseRes.pageData = pageData;
                baseRes.list = list;
                response = JsonUtile.obj2Json(baseRes);
                break;
            case DictionariesDocService.HOS_DOC_VIS_MSG:
                //修改随访备注
                doc = verifyTokenUser(req.token);
                if (doc == null) {
                    response = new MsgHint("100", "登陆过期，请重新登陆").toJson();
                    break;
                }
                VisitMsgReq visitMsgReq = (VisitMsgReq) JsonUtile.json2Obj(json, VisitMsgReq.class);
                if (!visitMsgReq.isVerifyParameter()) {
                    return visitMsgReq.hint;
                }
                response = VisitsManager.getInstance().onVisitMsgReq(getJdbcTemplate(), visitMsgReq);
                break;
            case DictionariesDocService.HOS_DOC_VIS_ADD:
                //添加随访
                doc = verifyTokenUser(req.token);
                if (doc == null) {
                    response = new MsgHint("100", "登陆过期，请重新登陆").toJson();
                    break;
                }
                VisitAddReq visitAddReq = (VisitAddReq) JsonUtile.json2Obj(json, VisitAddReq.class);
                if (!visitAddReq.isVerifyParameter()) {
                    return visitAddReq.hint;
                }
                response = VisitsManager.getInstance().onVisitAddReq(getJdbcTemplate(), doc.getDocId(),
                        visitAddReq);
                break;
            case DictionariesDocService.HOS_DOC_VIS_UPDATE:
                //修改随访
                doc = verifyTokenUser(req.token);
                if (doc == null) {
                    response = new MsgHint("100", "登陆过期，请重新登陆").toJson();
                    break;
                }
                VisitUpdateReq visitUpdateReq = (VisitUpdateReq) JsonUtile.json2Obj(json, VisitUpdateReq.class);
                if (!visitUpdateReq.isVerifyParameter()) {
                    return visitUpdateReq.hint;
                }
                response = VisitsManager.getInstance().onVisitUpdateReq(getJdbcTemplate(), visitUpdateReq);
                break;
            case DictionariesDocService.HOS_DOC_VIS_DELETE:
                //删除随访
                doc = verifyTokenUser(req.token);
                if (doc == null) {
                    response = new MsgHint("100", "登陆过期，请重新登陆").toJson();
                    break;
                }
                VisitDeleteReq visitDeleteReq = (VisitDeleteReq) JsonUtile.json2Obj(json, VisitDeleteReq.class);
                if (!visitDeleteReq.isVerifyParameter()) {
                    return visitDeleteReq.hint;
                }
                response = VisitsManager.getInstance().onVisitDeleteReq(getJdbcTemplate(), visitDeleteReq);
                break;
            //================科普文章====================
            case DictionariesDocService.HOS_DOC_ARTS:
                List<ArtEntity> arts = ArtManager.getInstance().getIssueArts(getJdbcTemplate(),
                        req.pageNo, req.pageSize, true);
                patSize = arts.size();
                baseRes = new BaseResponse();
                pageData = new PageData();
                if (patSize > req.pageSize) {
                    //有下一页
                    arts.remove(patSize - 1);
                    pageData.hasNextPage = true;
                }
                pageData.pageNo = req.pageNo;
                pageData.pageSize = arts.size();
                baseRes.pageData = pageData;
                baseRes.list = arts;
                response = JsonUtile.obj2Json(baseRes);
                break;
            //==========================医患关系==============================================
            case DictionariesDocService.HOS_DOC_RELATION_REMARK:
                //添加备注
                doc = verifyTokenUser(req.token);
                if (doc == null) {
                    response = new MsgHint("100", "登陆过期，请重新登陆").toJson();
                    break;
                }
                RelationRemarkReq relationRemarkReq = (RelationRemarkReq) JsonUtile.json2Obj(json,
                        RelationRemarkReq.class);
                if (!relationRemarkReq.isVerifyParameter()) {
                    return relationRemarkReq.hint;
                }
                response = RelationManager.getInstance().onUpdateRemark(getJdbcTemplate(),
                        relationRemarkReq.relationId, relationRemarkReq.remarkName,
                        relationRemarkReq.remarkImages);
                break;
            case DictionariesDocService.HOS_DOC_RELATION_PTAS:
                //获取患者
                doc = verifyTokenUser(req.token);
                if (doc == null) {
                    response = new MsgHint("100", "登陆过期，请重新登陆").toJson();
                    break;
                }
                List<UserPatsEntity> pats = RelationManager.getInstance().onPats(getJdbcTemplate(),
                        doc.getDocId(), req.pageNo, req.pageSize, true);
                patSize = pats.size();
                baseRes = new BaseResponse();
                pageData = new PageData();
                if (patSize > req.pageSize) {
                    //有下一页
                    pats.remove(patSize - 1);
                    pageData.hasNextPage = true;
                }
                pageData.pageNo = req.pageNo;
                pageData.pageSize = pats.size();
                baseRes.pageData = pageData;
                baseRes.list = pats;
                response = JsonUtile.obj2Json(baseRes);
                break;
            //=================系统消息======================
            case DictionariesDocService.HOS_DOC_MSG:
                //获取系统消息
                doc = verifyTokenUser(req.token);
                if (doc == null) {
                    response = new MsgHint("100", "登陆过期，请重新登陆").toJson();
                    break;
                }
                //
                List<MsgEntity> msgs = MsgManager.getInstance().onMsgsReq(getJdbcTemplate(),
                        doc.getDocId(), "", req.pageNo,
                        req.pageSize, true);
                patSize = msgs.size();
                baseRes = new BaseResponse();
                pageData = new PageData();
                if (patSize > req.pageSize) {
                    //有下一页
                    msgs.remove(patSize - 1);
                    pageData.hasNextPage = true;
                }
                pageData.pageNo = req.pageNo;
                pageData.pageSize = msgs.size();
                baseRes.pageData = pageData;
                baseRes.list = msgs;
                response = JsonUtile.obj2Json(baseRes);
                break;
            //==========================咨询==============================================
            case DictionariesDocService.HOS_DOC_CON:
                //咨询 列表
                doc = verifyTokenUser(req.token);
                if (doc == null) {
                    response = new MsgHint("100", "登陆过期，请重新登陆").toJson();
                    break;
                }
                ConsultsReq consultsReq = (ConsultsReq) JsonUtile.json2Obj(json,
                        ConsultsReq.class);

                List<ConsultPatEntity> cons = ConsultManager.getInstance().onDocConsults(getJdbcTemplate(),
                        doc.getDocId(), consultsReq.type, req.pageNo,
                        req.pageSize, true);
                patSize = cons.size();
                baseRes = new BaseResponse();
                pageData = new PageData();
                if (patSize > req.pageSize) {
                    //有下一页
                    cons.remove(patSize - 1);
                    pageData.hasNextPage = true;
                }
                pageData.pageNo = req.pageNo;
                pageData.pageSize = cons.size();
                baseRes.pageData = pageData;
                baseRes.list = cons;
                response = JsonUtile.obj2Json(baseRes);
                break;
            case DictionariesDocService.HOS_DOC_CON_END:
                //结束咨询
                doc = verifyTokenUser(req.token);
                if (doc == null) {
                    response = new MsgHint("100", "登陆过期，请重新登陆").toJson();
                    break;
                }
                ConsultIdReq endReq = (ConsultIdReq) JsonUtile.json2Obj(json,
                        ConsultIdReq.class);
                if (!endReq.isVerifyParameter()) {
                    return endReq.hint;
                }
                response = ConsultManager.getInstance().onConsultEndReq(getJdbcTemplate(),
                        endReq.consultId, endReq.userId);
                break;
            case DictionariesDocService.HOS_DOC_CON_ID:
                //获取咨询
                doc = verifyTokenUser(req.token);
                if (doc == null) {
                    response = new MsgHint("100", "登陆过期，请重新登陆").toJson();
                    break;
                }
                ConsultIdReq consultIdReq = (ConsultIdReq) JsonUtile.json2Obj(json,
                        ConsultIdReq.class);
                if (!consultIdReq.isVerifyParameter()) {
                    return consultIdReq.hint;
                }
                response = ConsultManager.getInstance().onDocConsultsReq(getJdbcTemplate(),
                        consultIdReq.consultId);
                break;
            //==========================咨询聊天==============================================
            case DictionariesDocService.HOS_DOC_CON_CHATS:
                //咨询聊天
                doc = verifyTokenUser(req.token);
                if (doc == null) {
                    response = new MsgHint("100", "登陆过期，请重新登陆").toJson();
                    break;
                }
                ConsultChatsReq consultChatsReq = (ConsultChatsReq) JsonUtile.json2Obj(json,
                        ConsultChatsReq.class);
                if (!consultChatsReq.isVerifyParameter()) {
                    return consultChatsReq.hint;
                }
                List<ConsultChatEntity> chats = ConsultChatManager.getInstance().onConsultChats(getJdbcTemplate(),
                        consultChatsReq.consultId, req.pageNo,
                        req.pageSize, true);
                patSize = chats.size();
                baseRes = new BaseResponse();
                pageData = new PageData();
                if (patSize > req.pageSize) {
                    //有下一页
                    chats.remove(0);
                    pageData.hasNextPage = true;
                }
                pageData.pageNo = req.pageNo;
                pageData.pageSize = chats.size();
                baseRes.pageData = pageData;
                baseRes.list = chats;
                response = JsonUtile.obj2Json(baseRes);
                break;

            case DictionariesDocService.HOS_DOC_CON_CHAT_ADD:
                //咨询聊天添加
                doc = verifyTokenUser(req.token);
                if (doc == null) {
                    response = new MsgHint("100", "登陆过期，请重新登陆").toJson();
                    break;
                }
                ConsultChatAddReq consultChatAddReq = (ConsultChatAddReq) JsonUtile.json2Obj(json,
                        ConsultChatAddReq.class);
                if (!consultChatAddReq.isVerifyParameter()) {
                    return consultChatAddReq.hint;
                }
                consultChatAddReq.consultSendType = "doc";
                response = ConsultChatManager.getInstance().onConsultChatAddReq(getJdbcTemplate(),
                        consultChatAddReq);
                break;
            //---------------推送id---------------------
            case DictionariesDocService.HOS_DOC_PUSH_ID:
                //上传推送id
                doc = verifyTokenUser(req.token);
                if (doc == null) {
                    response = new MsgHint("100", "登陆过期，请重新登陆").toJson();
                    break;
                }
                PushReq pushReq = (PushReq) JsonUtile.json2Obj(json,
                        PushReq.class);
                String pushId = pushReq.pushId;
                response = DocsManager.getInstance().updatePushId(getJdbcTemplate(),
                        doc.getDocId(), pushId);
                break;
            //---------------文件上传token---------------------
            case DictionariesDocService.HOS_DOC_FILE_TOKEN:
                //获取7牛上传的token
                String token = Yun7NManager.getInstance().getToken();
                BaseResponse res = new BaseResponse();
                Upload7NRes upload7NRes = new Upload7NRes();
                upload7NRes.token = token;

                res.obj = upload7NRes;
                response = res.toJson("0", "获取上传凭证成功");
                break;
            default:
                doc = verifyTokenUser(req.token);
                if (doc == null) {
                    response = new MsgHint("100", "登陆过期，请重新登陆").toJson();
                    break;
                }
                if (DictionariesIllService.isIllService(service)) {
                    response = onIll(service, json, doc, null, null);
                    break;
                }
                if (DictionariesFileService.isUplaodingService(service)) {
                    response = onUploading(service, json, doc, null, null);
                    break;
                }
                response = new MsgHint("请求未定义").toJson();
                break;
        }
        return response;
    }

    //需要登陆才能操作
    private boolean verifyToken(String token) {
        return verifyTokenUser(token) != null;
    }

    private UserDocEntity verifyTokenUser(String token) {
        return DocsManager.getInstance().verifyTokenUser(getJdbcTemplate(), token);
    }
}
